package com.face.server.service.impl;

import com.arcsoft.AFR_FSDK_FACEMODEL;
import com.arcsoft.ASVLOFFSCREEN;
import com.arcsoft.FaceInfo;
import com.face.RespMsg;
import com.face.client.model.NotFoundFaceException;
import com.face.server.entity.FaceModel;
import com.face.server.repository.FaceModelRepository;
import com.face.server.repository.JoinedRepository;
import com.face.server.dao.JoinedDAO;
import com.face.server.entity.Auth;
import com.face.server.entity.Student;
import com.face.server.service.IFaceDetectService;
import com.face.server.service.UtileService;
import com.util.FaceUtils;
import com.util.ImageUtils;
import com.util.JWTUtils;
import com.util.SDKUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 用户登陆
 */
@Service
public class UserLoginService {

    @Autowired
    JoinedDAO joinedDAO;

    @Autowired
    FaceDetectImpl faceDetectService;

    @Autowired
    JoinedRepository joinedRepository;

    @Autowired
    UtileService utileService;

    @Autowired
    FaceModelRepository faceModelRepository;

    public RespMsg checkUser(@NotNull Auth auth,
                             HttpServletResponse response) {
        Student student = joinedDAO.findByUserNameAndType(auth.getUsername());
        if (student == null) {
            return RespMsg.error("用户名不存在");
        } else if (!passwordEq(auth, student)) {
            return RespMsg.error("密码错误");
        }  else {
            String jwt = JWTUtils.createJWT("auth", student);
            response.setHeader("jwt", jwt);
            return RespMsg.build("登陆成功");
        }
    }

    private boolean passwordEq(@NotNull Auth auth, Student student) {
        String passwd = student.getAuth().getPassword();
        return passwd != null && passwd.equals(auth.getPassword());
    }


    public RespMsg getStudentById(@NotNull String id) {
        Student student = joinedDAO.findOne(id);
        if (student == null) {
            return RespMsg.error("找不到该id的用户信息");
        } else {
            return RespMsg.build(student);
        }
    }

    /**
     * @param student 带有id，status，phone，name
     * @return
     */
    public RespMsg update(Student student) {
        int i = joinedDAO.updateProject(student);
        return i == 1 ? RespMsg.build("更新成功") : RespMsg.error("更新失败");
    }

    public RespMsg savePrePhoto(MultipartFile file, String studentId) throws IOException {
        String proPhoto = utileService.upFile(file);
        Student student = new Student();
        student.getAuth().setProPhoto(proPhoto);
        student.setId(studentId);
        int i = joinedDAO.updateProPhoto(student);
        return i == 1 ? RespMsg.build("更新成功") : RespMsg.error("更新失败");
    }


    public RespMsg saveFaceModels(MultipartFile file, String id) throws IOException {
        Student student = joinedDAO.findOne(id);
        return faceDetectService.saveFaceModels(file, student);
    }


    public RespMsg deleteFaceModel(String id, String fileId) throws InterruptedException,
            ExecutionException {
        return CompletableFuture.allOf(
                CompletableFuture.supplyAsync(() -> faceModelRepository.findByFileId(fileId))
                        .thenAccept(faceModel -> joinedDAO.removeFaceModel(id, faceModel))
                        .thenAccept(aVoid -> utileService.delete(fileId)),
                CompletableFuture.runAsync(() -> faceModelRepository.deleteByFileId(fileId))
        ).handle((aVoid, throwable) -> {
            if (throwable != null) {
                return RespMsg.error(throwable.getMessage());
            } else return RespMsg.build("删除成功");
        }).get();
    }




}
